package com.ruoyi.web.controller.system;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;

import cn.hutool.core.util.IdUtil;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;

import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.core.config.Constants;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.KpiPerformanceMonthly;
import com.ruoyi.system.service.IKpiPerformanceMonthlyService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;


/**
 * 月度绩效管理Controller
 * 
 * @author wurb
 * @date 2024-01-23
 */
@RestController
@RequestMapping("/system/monthly")
public class KpiPerformanceMonthlyController extends BaseController
{
    @Autowired
    private IKpiPerformanceMonthlyService kpiPerformanceMonthlyService;

    @Resource
    private ISysUserService userService;

    @Resource
    private ISysDictDataService sysDictDataService;

    @Resource
    private ISysDeptService sysDeptService;

    @Resource
    private ISysPostService sysPostService;

    /**
     * 查询月度绩效管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:monthly:list')")
    @GetMapping("/list")
    public TableDataInfo list(KpiPerformanceMonthly kpiPerformanceMonthly)
    {
        startPage();
        List<KpiPerformanceMonthly> list = kpiPerformanceMonthlyService.selectKpiPerformanceMonthlyList(kpiPerformanceMonthly);
        return getDataTable(list);
    }

    /**
     * 查询月度绩效管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:monthly:listAudit')")
    @GetMapping("/listAudit")
    public TableDataInfo listAudit(KpiPerformanceMonthly kpiPerformanceMonthly)
    {
        startPage();
        //获取登陆用户信息
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();

        /**
         * 判断权限是否为组长
         * 如果为组长或经理，可查询本部门所有人员的绩效
         */

        if (Constants.MANAGER_ROLE_ID.equals(user.getRoleId())
            || Constants.TEAMLEADER_ROLE_ID.equals(user.getRoleId())){

            kpiPerformanceMonthly.setDeptId(user.getDeptId());
        }

        List<KpiPerformanceMonthly> list = kpiPerformanceMonthlyService.selectKpiPerformanceMonthlyList(kpiPerformanceMonthly);
        return getDataTable(list);
    }

    /**
     * 导出月度绩效管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:monthly:export')")
    @Log(title = "月度绩效管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, KpiPerformanceMonthly kpiPerformanceMonthly)
    {
        List<KpiPerformanceMonthly> list = kpiPerformanceMonthlyService.selectKpiPerformanceMonthlyList(kpiPerformanceMonthly);
        ExcelUtil<KpiPerformanceMonthly> util = new ExcelUtil<KpiPerformanceMonthly>(KpiPerformanceMonthly.class);
        util.exportExcel(response, list, "月度绩效管理数据");
    }

    /**
     * 获取月度绩效管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:monthly:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(kpiPerformanceMonthlyService.selectKpiPerformanceMonthlyById(id));
    }

    /**
     * 新增月度绩效管理
     */
    @PreAuthorize("@ss.hasPermi('system:monthly:add')")
    @Log(title = "月度绩效管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody KpiPerformanceMonthly kpiPerformanceMonthly)
    {

        //获取登陆用户信息
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();

        kpiPerformanceMonthly.setStateId(Constants.ALREADY_SUBMIT_ORDER_STATE_ID);
        kpiPerformanceMonthly.setStateName(sysDictDataService.selectDictLabel("kpi_order_state_type",kpiPerformanceMonthly.getStateId()));

        kpiPerformanceMonthly.setId(IdUtil.getSnowflakeNextId());
        kpiPerformanceMonthly.setCreatorId(user.getUserId());
        kpiPerformanceMonthly.setCreateBy(user.getNickName());
        kpiPerformanceMonthly.setCreatorName(user.getUserName());
        kpiPerformanceMonthly.setCreateTime(DateUtil.date());
        kpiPerformanceMonthly.setDeptId(user.getDeptId());
        kpiPerformanceMonthly.setDeptName(user.getDept().getDeptName());

        KpiPerformanceMonthly kpiPerformanceMonthlySelect = kpiPerformanceMonthlyService
            .selectKpiPerformanceMonthlyByuserIdandDate(kpiPerformanceMonthly);

        if (ObjectUtil.isNotEmpty(kpiPerformanceMonthlySelect))
        {
            return error("您本月已提交绩效考评，请勿重复提交！");
        }

        return toAjax(kpiPerformanceMonthlyService.insertKpiPerformanceMonthly(kpiPerformanceMonthly));
    }

    /**
     * 修改月度绩效管理
     */
    @PreAuthorize("@ss.hasPermi('system:monthly:edit')")
    @Log(title = "月度绩效管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody KpiPerformanceMonthly kpiPerformanceMonthly)
    {
        return toAjax(kpiPerformanceMonthlyService.updateKpiPerformanceMonthly(kpiPerformanceMonthly));
    }

    /**
     * 删除月度绩效管理
     */
    @PreAuthorize("@ss.hasPermi('system:monthly:remove')")
    @Log(title = "月度绩效管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(kpiPerformanceMonthlyService.deleteKpiPerformanceMonthlyByIds(ids));
    }

    /**
     * 获取个人月度绩效录入管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:monthly:query')")
    @RequestMapping(value = "/addMonthlyList",method = RequestMethod.GET)
    public AjaxResult addMonthlyList()
    {
        //获取登陆用户信息
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();

        //获取登陆用户岗位
        List<SysPost> postGroup = userService.selectUserPost(loginUser.getUsername());

        String postName = postGroup.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
        Long postId = postGroup.get(0).getPostId();

        //获取上个月日期
        DateTime dateTime = DateUtil.lastMonth();


        KpiPerformanceMonthly kpiPerformanceMonthly = new KpiPerformanceMonthly();

        kpiPerformanceMonthly.setEmployeeName(user.getNickName());
        kpiPerformanceMonthly.setEmployeeId(user.getUserId());
        kpiPerformanceMonthly.setJobName(postName);
        kpiPerformanceMonthly.setJobId(postId.toString());
        kpiPerformanceMonthly.setPerformanceDate(dateTime);

        return success(kpiPerformanceMonthly);
    }

    /**
     * 对处于员工已提交状态的绩效单进行撤回操作
     *
     */
    @PreAuthorize("@ss.hasPermi('system:monthly:back')")
    @RequestMapping(value = "/backMonthly/{id}",method = RequestMethod.GET)
    public AjaxResult backMonthly(@PathVariable("id") Long id)
    {
        //查询工单状态
        KpiPerformanceMonthly kpiPerformanceMonthly = kpiPerformanceMonthlyService
            .selectKpiPerformanceMonthlyById(id);

        /**判断工单状态是否为员工已提交
          *如果工单状态为员工已提交，则允许将工单进行撤回。
          */
        if (Constants.ALREADY_SUBMIT_ORDER_STATE_ID.equals(kpiPerformanceMonthly.getStateId())){

            kpiPerformanceMonthly.setStateId(Constants.STAFF_BACK_ORDER_STATE_ID);
            kpiPerformanceMonthly.setStateName(sysDictDataService.selectDictLabel("kpi_order_state_type",kpiPerformanceMonthly.getStateId()));
            kpiPerformanceMonthlyService.updateKpiPerformanceMonthly(kpiPerformanceMonthly);
            return success("工单撤回成功");
        }else{
            return error("当前工单状态为【"+ kpiPerformanceMonthly.getStateName() + "】，不允许撤回！");
        }

    }

    /**
     * 查询已提交月度绩效用户
     *
     */
    @PreAuthorize("@ss.hasPermi('system:monthly:list')")
    @RequestMapping(value = "/listMonthlyAuditSubmitDetail",method = RequestMethod.GET)
    public TableDataInfo listMonthlyAuditSubmitDetail( KpiPerformanceMonthly kpiPerformanceMonthly){

        //获取登陆用户信息
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();

        if (!user.isAdmin() && !user.getRoleId().equals(Constants.LEADERS_ROLE_ID))
        {
            if (ObjectUtil.isEmpty(kpiPerformanceMonthly.getPerformanceDate())) {
                kpiPerformanceMonthly.setPerformanceDate(DateUtil.date());
            }

            kpiPerformanceMonthly.setDeptId(user.getDeptId());

                //查询已提交的用户情况
            List<KpiPerformanceMonthly> list = kpiPerformanceMonthlyService
                .selectSubmitDetails(kpiPerformanceMonthly);
            return getDataTable(convertList(list,kpiPerformanceMonthly.getPerformanceDate()));

        }else{
            if (ObjectUtil.isEmpty(kpiPerformanceMonthly.getPerformanceDate())) {
                kpiPerformanceMonthly.setPerformanceDate(DateUtil.date());
            }
                //查询已提交的用户情况
            List<KpiPerformanceMonthly> list = kpiPerformanceMonthlyService
                .selectSubmitDetails(kpiPerformanceMonthly);
            return getDataTable(convertList(list,kpiPerformanceMonthly.getPerformanceDate()));

        }


    }

    /**
     * 查询未提交月度绩效用户
     *
     */
    @PreAuthorize("@ss.hasPermi('system:monthly:list')")
    @RequestMapping(value = "/listMonthlyAuditNoSubmitDetail",method = RequestMethod.GET)
    public TableDataInfo listMonthlyAuditNoSubmitDetail( KpiPerformanceMonthly kpiPerformanceMonthly){

        startPage();
        //获取登陆用户信息
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();

        if (!user.isAdmin() && !user.getRoleId().equals(Constants.LEADERS_ROLE_ID))
        {
            if (ObjectUtil.isEmpty(kpiPerformanceMonthly.getPerformanceDate())) {
                kpiPerformanceMonthly.setPerformanceDate(DateUtil.date());
            }

            kpiPerformanceMonthly.setDeptId(user.getDeptId());

            //查询已提交的用户情况
            List<KpiPerformanceMonthly> list =  kpiPerformanceMonthlyService
                .selectNoSubmitDetails(kpiPerformanceMonthly);
            return getDataTable(convertList(list,kpiPerformanceMonthly.getPerformanceDate()));

        }else{
            if (ObjectUtil.isEmpty(kpiPerformanceMonthly.getPerformanceDate())) {
                kpiPerformanceMonthly.setPerformanceDate(DateUtil.date());
            }
            //查询已提交的用户情况
            List<KpiPerformanceMonthly> list =  kpiPerformanceMonthlyService
                .selectNoSubmitDetails(kpiPerformanceMonthly);
            return getDataTable(convertList(list,kpiPerformanceMonthly.getPerformanceDate()));

        }
    }

    /**
     * 直线经理打分
     *
     */
    @PreAuthorize("@ss.hasPermi('system:monthly:managerAudit')")
    @RequestMapping(value = "/updateManagerMonthly",method = RequestMethod.POST)
    public AjaxResult updateManagerMonthly(KpiPerformanceMonthly kpiPerformanceMonthly){
        //获取登陆用户信息
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();

        //根据id查询绩效工单记录，并在此实体上进行更新
        KpiPerformanceMonthly updateKpiPerformanceMonthly = kpiPerformanceMonthlyService
            .selectKpiPerformanceMonthlyById(kpiPerformanceMonthly.getId());

        updateKpiPerformanceMonthly.setStateId(Constants.GROUP_AUDIT_ORDER_STATE_ID);
        updateKpiPerformanceMonthly.setStateName(sysDictDataService.selectDictLabel("kpi_order_state_type", Constants.GROUP_AUDIT_ORDER_STATE_ID));

        updateKpiPerformanceMonthly.setItemGroupOpinion(kpiPerformanceMonthly.getItemGroupOpinion());
        updateKpiPerformanceMonthly.setTaskGroupOpinion(kpiPerformanceMonthly.getTaskGroupOpinion());
        updateKpiPerformanceMonthly.setGroupMemberId(user.getUserId());
        updateKpiPerformanceMonthly.setGroupMemberName(user.getNickName());
        updateKpiPerformanceMonthly.setGroupMemberTime(DateUtil.date());

        return toAjax(kpiPerformanceMonthlyService.updateKpiPerformanceMonthly(updateKpiPerformanceMonthly));
    }

    /**
     * 直线经理打分
     *
     */
    @PreAuthorize("@ss.hasPermi('system:monthly:groupAudit')")
    @RequestMapping(value = "/updateGroupMonthly",method = RequestMethod.POST)
    public AjaxResult updateGroupMonthly(KpiPerformanceMonthly kpiPerformanceMonthly){

        //获取登陆用户信息
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();

        //根据id查询绩效工单记录，并在此实体上进行更新
        KpiPerformanceMonthly updateKpiPerformanceMonthly = kpiPerformanceMonthlyService
            .selectKpiPerformanceMonthlyById(kpiPerformanceMonthly.getId());

        updateKpiPerformanceMonthly.setStateId(Constants.MANAGER_AUDIT_ORDER_STATE_ID);
        updateKpiPerformanceMonthly.setStateName(sysDictDataService.selectDictLabel("kpi_order_state_type", Constants.MANAGER_AUDIT_ORDER_STATE_ID));

        updateKpiPerformanceMonthly.setItemManagerScore(kpiPerformanceMonthly.getItemManagerScore());
        updateKpiPerformanceMonthly.setItemManagerOpinion(kpiPerformanceMonthly.getItemManagerOpinion());
        updateKpiPerformanceMonthly.setTaskManagerOpinion(kpiPerformanceMonthly.getTaskManagerOpinion());
        updateKpiPerformanceMonthly.setTaskManagerScore(kpiPerformanceMonthly.getTaskManagerScore());

        updateKpiPerformanceMonthly.setManagerId(user.getUserId());
        updateKpiPerformanceMonthly.setManagerName(user.getNickName());
        updateKpiPerformanceMonthly.setManagerDatetime(DateUtil.date());

        return toAjax(kpiPerformanceMonthlyService.updateKpiPerformanceMonthly(updateKpiPerformanceMonthly));
    }

    public List<KpiPerformanceMonthly> convertList(List<KpiPerformanceMonthly> list,
        Date performanceDate){
        for (Iterator<KpiPerformanceMonthly> iterator= list.iterator(); iterator.hasNext();){
            KpiPerformanceMonthly kpiPerformanceMonthly = iterator.next();
            List<SysPost> posts =sysPostService.selectPostsByUserId(kpiPerformanceMonthly.getEmployeeId());

            //获取岗位名称
            if (!ObjectUtil.isEmpty(posts)){

                kpiPerformanceMonthly.setJobName(posts.get(0).getPostName());
            }

            kpiPerformanceMonthly.setDeptName(sysDeptService.selectDeptById(kpiPerformanceMonthly.getDeptId()).getDeptName());
            kpiPerformanceMonthly.setPerformanceDate(performanceDate);

        }

        return list;

    }

}
